﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace PMS.Controllers.BD
{
    public class RoleController : Controller
    {
        //
        // GET: /Role/

        public ActionResult RoleList()
        {
            return View();
        }
        public ActionResult AssignRoleWindow()
        {
            return View();
        }
        public void GetRoleList()
        {
            List<BD_Role> list = BLLSession.Current.BD_RoleBLL.GetPagedList(OperateContext.Page, OperateContext.Rows, r => 1 == 1, u => u.Id, true).ToList();
            int count = BLLSession.Current.BD_RoleBLL.GetCount(r => 1 == 1);
            Response.Write(JsonHelper.toPageJson(list, count));
        }
        public void AddRole()
        {
            BD_Role role = new BD_Role() { AddTime = DateTime.Now.ToString("yyyy-MM-dd") };
            ModelTools.Form2Model(Request.Form, role);
            BLLSession.Current.BD_RoleBLL.Add(role);
            Response.Write(JsonHelper.toDefaultMsg(true));
        }
        public void EditRole()
        {
            int Id = Commons.String2Int32(Request.Form["Id"]);
            BD_Role perNew = BLLSession.Current.BD_RoleBLL.GetListBy(d => d.Id == Id).FirstOrDefault();
            ModelTools.Form2EditModel(Request.Form, perNew);
            perNew.AddTime = DateTime.Now.ToString("yyyy:MM:dd,HH:mm:ss");
            BLLSession.Current.BD_RoleBLL.ModifyAllModel(perNew);
            Response.Write(JsonHelper.toDefaultMsg(true, "保存成功"));
        }
        //删除角色
        public void DelRole()
        {
            int Id = Convert.ToInt32(Request.Form["Id"].ToString());
            BLLSession.Current.BD_RoleBLL.DelBy(p => p.Id == Id);
            Response.Write(JsonHelper.toDefaultMsg(true, "删除成功"));
        }

        /// <summary>
        /// 获取权限树，如果传的参数是角色，则获取角色权限树，如果传的参数是用户Id，则获取是特权权限树
        /// </summary>
        public JsonResult GetPermTree()
        {
            int roleId = Commons.String2Int32(Request.Form["roleId"]);
            List<TreeNode> listNodes = new List<TreeNode>();
            var showList = BLLSession.Current.BD_PermissionBLL.GetListBy(p => p.IsShow == "0");
            LoadTreeNode(showList, listNodes, 0, roleId);
            return Json(listNodes);
        }
        private void LoadTreeNode(List<BD_Permission> listPer, List<TreeNode> listNodes, int pid, int roleId)
        {
            //foreach (var permission in listPer)
            //{
            for (int i = 0; i < listPer.Count; i++)
            {
                if (listPer[i].Parent == pid)
                {
                    int currentpid=listPer[i].Id;
                    bool hasright = BLLSession.Current.BD_RolePermissionBLL.isExists(u => u.RId == roleId && u.PId == currentpid);
                    TreeNode node = new TreeNode()
                    {
                        id = currentpid,
                        text = listPer[i].Name,
                        Checked = false,
                        attributes = new { isParent = listPer[i].IsFatherNode, isHasRight = hasright },
                        children = new List<TreeNode>()
                    };
                    if (listPer.Count(p => p.Parent == listPer[i].Id) > 0)
                    {
                        node.state = "closed";
                    }
                    else
                    {
                        node.state = "open";
                    }
                    listNodes.Add(node);
                    LoadTreeNode(listPer, node.children, node.id, roleId);
                }
            }
        }


        /// <summary>
        /// 获取角色权限树
        /// </summary>
        public void GetRolePermTree()
        {
            //int roleId = Convert.ToInt32(Request.Form["Id"]);
            //List<BD_Permission> perm = Permission.GetAllPerm();
            //List<BD_Permission> rolePerm = Permission.GetPermByRole(roleId);
            //List<TreeNode> node = Permission.GetPerTreeBySubTree(perm, rolePerm);
            //string nodeStr = JsonHelper.toJson(node);
            //string newNodeStr = nodeStr.Replace("Checked", "checked");
            //Response.Write(JsonHelper.toJson(newNodeStr));
        }
        /// <summary>
        /// 修改角色权限树
        /// </summary>
        public void EditRolePermTree()
        {
            int roleId = Commons.String2Int32(Request.Form["roleId"]);
            int perId = Commons.String2Int32(Request.Form["perId"]);
            string hasRight = Request.Form["hasRight"];
            if(hasRight=="true")
            {
                if (!BLLSession.Current.BD_RolePermissionBLL.isExists(u => u.RId == roleId && u.PId == perId))//如果现在被选中的不存在于权限表中，则是新选中的，添加权限
                {
                    BD_RolePermission newinfo = new BD_RolePermission();
                    newinfo.RId = roleId;
                    newinfo.PId = perId;
                    BLLSession.Current.BD_RolePermissionBLL.Add(newinfo);
                }
            }
            else
            {
                if (BLLSession.Current.BD_RolePermissionBLL.isExists(u => u.RId == roleId && u.PId == perId))//如果现在未被选中的存在于权限表中，则是新取消的，删除权限
                {
                    BLLSession.Current.BD_RolePermissionBLL.DelBy(u => u.RId == roleId && u.PId == perId);
                }
            }
            string dataString = Request.Form["data"];
            List<View_BD_btnPermission> detailList = JsonConvert.DeserializeObject<List<View_BD_btnPermission>>(dataString);
            for (int k = 0; k < detailList.Count; k++)
            {
                int bid = detailList[k].Id;
                if (detailList[k].isChecked == true)
                {
                    if (!BLLSession.Current.BD_RoleBtnPermissionBLL.isExists(u => u.RId == roleId && u.BId == bid))//如果现在被选中的不存在于权限表中，则是新选中的，添加权限
                    {
                        BD_RoleBtnPermission newinfo = new BD_RoleBtnPermission();
                        newinfo.RId = roleId;
                        newinfo.BId = bid;
                        BLLSession.Current.BD_RoleBtnPermissionBLL.Add(newinfo);
                    }
                }
                else
                {
                    if (BLLSession.Current.BD_RoleBtnPermissionBLL.isExists(u => u.RId == roleId && u.BId == bid))//如果现在未被选中的存在于权限表中，则是新取消的，删除权限
                    {
                        BLLSession.Current.BD_RoleBtnPermissionBLL.DelBy(u => u.RId == roleId && u.BId == bid);
                    }
                }
            }
            Response.Write(JsonHelper.toDefaultMsg(true, "保存成功！"));
        }
        //获取该角色的权限按钮的树节点
        public void GetRoleBtnPer()
        {
            //获取角色的ID
            int roleId = Convert.ToInt32(Request.Form["Id"]);
            //获取角色的所有权限二级页面
            List<BD_Permission> rolePerm = Permission.GetPermByRoleEr(roleId);
            //获取该角色选中的按钮权限Id集合
            List<int> roleBtnPerm = Permission.GetBtnPermIdListByRole(roleId);
            //获取用户所有权限二级页面下的按钮
            List<BD_btnPermission> allBtnPerm = Permission.GetAllBtnPerm(rolePerm);
            //创建树节点
            List<TreeNode> node = Permission.GetBtnTree(rolePerm, allBtnPerm, roleBtnPerm);
            string nodeStr = JsonHelper.toJson(node).Replace("Checked", "checked");
            Response.Write(nodeStr);
        }
        //更改该角色的权限按钮
        public void EditRoleBtnPermTree()
        {
            //获取角色的ID
            int roleId = Convert.ToInt32(Request.Form["Id"]);
            List<int> nodes = new List<int>();
            string nodesStr = Request.Form["PermIds"].ToString();
            for (int i = 0; i < nodesStr.Trim(',').Split(',').Length; i++)
            {
                nodes.Add(Commons.String2Int32(nodesStr.Trim(',').Split(',')[i]));
            }
            BLLSession.Current.BD_RoleBtnPermissionBLL.DelBy(p => p.RId == roleId);
            foreach (var PId in nodes)
            {
                BLLSession.Current.BD_RoleBtnPermissionBLL.Add(new BD_RoleBtnPermission() { RId = roleId, BId = PId });
            }
            Response.Write(JsonHelper.toDefaultMsg(true));
        }
    }
}
